package services

import (
	"context"
	"wxapi/internal/svc"
	"wxapi/models"

	"gorm.io/gorm"
)

func GetDoctorBySkill(ctx context.Context, svc *svc.ServiceContext, storeId int64, skillIds ...int64) ([]*models.Doctor, error) {
	d2sList := make([]*models.DoctorSkill, 0)
	svc.Mysql.Select("doctor_id").Where("state = 100 AND skill_id in (?)", skillIds).Group("doctor_id").Find(&d2sList)

	dIdList := make([]int64, 0)
	for _, v := range d2sList {
		dIdList = append(dIdList, v.DoctorId)
	}
	doctorList := make([]*models.Doctor, 0)
	svc.Mysql.Model(&models.Doctor{}).Preload("Skills", func(db *gorm.DB) *gorm.DB {
		return db.Where("skill_id in (?)", skillIds).Order("`order`")
	}).Preload("Skills.Skill").Preload("Level").Preload("SellPoint").Where("store_id = ? AND state = 100 AND id in (?)", storeId, dIdList).Order("`order`").Find(&doctorList)

	return doctorList, nil
}

func GetDoctorInfo(ctx context.Context, svc *svc.ServiceContext, doctorId int64) (*models.Doctor, error) {
	doctor := &models.Doctor{}

	svc.Mysql.Model(&models.Doctor{}).Preload("Level").Preload("SellPoint").Where("state = 100 AND id = ?", doctorId).First(&doctor)

	return doctor, nil
}

func GetDoctorGoodAt(ctx context.Context, svc *svc.ServiceContext, doctorId int64) ([]*models.Skill, error) {
	d2s := make([]*models.DoctorSkill, 0)

	svc.Mysql.Preload("Skill").Where("state = 100 AND doctor_id = ?", doctorId).Find(&d2s)

	skillMap := make(map[int64]*models.Skill)
	for _, v := range d2s {
		if _, ok := skillMap[v.SkillId]; !ok {
			skillMap[v.SkillId] = v.Skill
		}
	}

	skillList := make([]*models.Skill, 0)
	for _, v := range skillMap {
		skillList = append(skillList, v)
	}

	return skillList, nil
}

func GetDoctorItems(ctx context.Context, svc *svc.ServiceContext, doctorId int64) ([]*models.DoctorSkill, error) {
	items := make([]*models.DoctorSkill, 0)

	svc.Mysql.Model(&models.DoctorSkill{}).Preload("Skill").Where("doctor_id = ? AND state = 100", doctorId).Order("`order`").Find(&items)

	return items, nil
}
